<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .box{
      width: 500px;
      height: 300px;
      background-image: url("three.jpg") ;
      background-size: cover;
      position: relative;
    }
    .img{
      background-position: -201px ;
      width: 80px;
      height: 80px;
      background-image: url("three.jpg") ;
      background-size: 500px;
      position: absolute;
      top: 110px;
      left:0;
      z-index: 1;

    }
    .gap{
      position: absolute;
      top: 110px;
      left: 221px;
      background: url("cat.jpg");
      width: 80px;
      height: 80px;
    }
  </style>
</head>
<body>
<div class="box" >
  <div class="img"></div>
  <div class="gap"></div>
</div>
<div class="move">
  <input type="range" class="range" name="range" max="100" min="1" value="1" style="width: 500px">
</div>

<script>

  var box = document.querySelector(".box");
  var img = document.querySelector(".img");
  var gap = document.querySelector(".gap");
  var move = document.querySelector(".move");
  var range = document.querySelector(".range");
  //获取容器得宽度和滑块得宽度
  var boxWidth = box.offsetWidth;
  var imgWidth = img.offsetWidth;

  document.addEventListener('DOMContentLoaded', function () {
    var number = ~~(Math.random()*4+1);
    console.log(number)

    if (number===1){
      box.style.backgroundImage = "url('cat.jpg')";
      img.style.backgroundImage = "url('cat.jpg')"

    }else if (number === 2){
      box.style.backgroundImage = "url('one.jpg')";
      img.style.backgroundImage = "url('one.jpg')"
    }else if (number === 3){
      box.style.backgroundImage ="url('two.jpg')";
      img.style.backgroundImage ="url('two.jpg')"
    }else {
      box.style.backgroundImage ="url('three.jpg')"
      img.style.backgroundImage ="url('three.jpg')"
    }
  });

  //随机生成 图片的缺口
  var imgKou =()=>{
    //生成缺口的范围在滑块之外，容器之内
    var left = ~~(Math.random()*(boxWidth-2*imgWidth))+imgWidth;
    //设置缺口的位置即设置它距离容器左侧的值
    gap.style.left = left +"px";
    //设置滑块背景图片位置，因为向左移动所以，应该是负数
    img.style.backgroundPosition = -left +"px";
    console.log("gap.style.left",gap.style.left);
    return left;
  }

  //获取当前缺口距离容器左侧的值
  var gapLeft = parseInt(imgKou());

  var imgLeft
  //拖动事件绑定
  move.addEventListener('input',function (e){
    //根据滑动条滑动，设置滑块距离容器左侧的值
    img.style.left = (e.target.value/100)*(boxWidth-imgWidth)+"px";
    imgLeft = parseInt(img.style.left);
    console.log("imgLeft===",imgLeft);
  })
  move.onmouseup = function () {
    if (Math.abs(imgLeft-gapLeft) < 5){
      alert("成功")
    }else {
      img.style.left = 0+"px";
      range.value = 1;
    }

  }


</script>
</body>
</html>